package github.full_stack_notes;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author : DRevelation
 * @Date : 2020/12/1 10:38
 */
public class AnnotationDemo {

    @Data
    @AllArgsConstructor
    static class Student {
        @Json(value = "姓名")
        private String name;
        @Json(value = "出生日期", format = "yyyy-MM-dd")
        private Date birthday;
    }

    static void parse(Object object, Class<?> clazz) throws IllegalAccessException {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Json.class)) {
                field.setAccessible(true);
                Object value = field.get(object);
                Json json = field.getAnnotation(Json.class);
                String name = json.value();
                String format = json.format();
                if (!"".equals(format) && field.getType() == Date.class) {
                    SimpleDateFormat sdf = new SimpleDateFormat(format);
                    value = sdf.format(value);
                }
                System.out.println(name + ":" + value);
            }
        }
    }

    public static void main(String[] args) throws IllegalAccessException {
        Student student = new Student("AA", new Date());
        parse(student, Student.class);
    }
}
